<template>
<!--  <h2>四性检测记录</h2>-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch">
      <el-form-item label="检测阶段" prop="detectionLink">
        <el-select v-model="queryParams.detectionLink" placeholder="请选择" clearable style="width: 240px">
          <el-option v-for="item in dict.type.DETECTION_PHASE" :key="item.value" :label="item.label"
                     :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd" v-hasPermi="['archive:fourNatures:detectionRecords:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit"  @click="handleUpdate" v-hasPermi="['archive:fourNatures:detectionRecords:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete"  @click="handleDelete" v-hasPermi="['archive:fourNatures:detectionRecords:delete']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download"  @click="handleExport" v-hasPermi="['archive:fourNatures:detectionRecords:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" :height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="id"/>

        <el-table-column label="检测环节" prop="detectionLink" align="center" >
          <template slot-scope="scope">
            {{ scope.row.detectionLink }}
            <!-- <span v-for="item in dict.type.DETECTION_PHASE" :key="item">{{scope.row.detectionLink==item.value?item.label:'' }} </span> -->
          </template>
      </el-table-column>
      <el-table-column label="检测结果" prop="detectionResult1" align="center" />
      <el-table-column label="检测时间" prop="detectionTime" align="center" />
      <el-table-column label="操作" width="350px" align="center" header-align="center">
        <template slot-scope="scope">
          <el-button  plain type="info" @click="handleDetail(scope.row)" v-hasPermi="['archive:fourNatures:detectionRecords:detail']">查看详情</el-button>
          <el-button  plain type="primary" @click="handleDh(scope.row)">查看档号</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body :before-close="cancel">
      <el-form :model="passForm" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="检测环节" prop="detectionLink">
              <el-select v-model="passForm.detectionLink" placeholder="请选择" :disabled="true" style="width: 90%">
                <el-option v-for="item in phaseOption" :key="item.value" :label="item.label"
                           :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检测时间" prop="detectionTime">
              <el-date-picker v-model="passForm.detectionTime" type="datetime" placeholder="选择日期" style="width: 90%" :disabled="true">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检测结果">
              <el-radio-group v-model="passForm.detectionResult">
                <el-radio :label="'0'">检测失败</el-radio>
                <el-radio :label="'1'">检测成功</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button  @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 方案明细 -->
    <!-- 四性方案 isShow: '1', 四性记录 isShow: '2' -->
    <planDetail v-if="planOpen" :open="planOpen" :title="planTitle" ref="planRef" :isShow="'2'" @planCancelTap="planCancelTap"></planDetail>

    <!-- 四性方案新增导入 -->
    <el-dialog :title="upload.title + '导入'" :visible.sync="upload.open" width="400px" style="margin-top:8%;" append-to-body :before-close="closeDelDialog">
      <div style="height: 100%; line-height: 50px; overflow: hidden; padding: 15px">
        <el-upload class="upload-file-demo" action="上传的url" ref="uploadComp" :auto-upload="true" :show-file-list='true' :on-change="handleChange"
                   :disabled="loading" accept="" :http-request="uploadFile" :file-list="fileList" :on-remove="handleRemove">
          <div style="width: 100%; display: flex">
            <el-button :loading="loading"  type="primary" icon="el-icon-upload" style="padding: 0 10px; height: 40px">上传文件</el-button>
            <span style="margin-left: 2%; white-space: nowrap;">仅允许导入xml格式文件。</span>
          </div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="closeDelDialog">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 档号 -->
    <el-dialog title="查看档号" :visible.sync="dhOpen" width="400px" append-to-body :before-close="closeDelDialog">
      <el-table v-loading="dhLoading" border :data="dhList" height="300">
        <el-table-column label="序号" type="index" width="55" align="center"/>
        <el-table-column label="档号" prop="dh" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import estimateTableHeight from "@/mixins/estimateTableHeight";
import PlanDetail from "@/views/archive/fourNatures/detectionPlan/planDetail";
import {
  addRecords,
  deleteRecords,
  getRecordsDetail,
  getRecordsList,
  updateRecords
} from "@/api/archive/fourNatures/detectionRecords";

export default {
  archive_Dicts: ['DETECTION_PHASE'],
  name: "index",
  mixins: [estimateTableHeight], // 混入方法
  components: { PlanDetail },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum:1,
        pageSize:10,
        detectionLink: undefined
      },
      // 检测阶段
      phaseOption: [],
      // 检测结果
      resultOption: [
        {value: '0', label: '检测失败'},
        {value: '1', label: '检测成功'}
      ],
      // 表格数据
      dataList: [],
      total: 0,

      // 方案明细弹窗
      planOpen: false,
      planTitle: '检测详情',
      info: [],

      title: '修改四性记录',
      open: false,
      passForm: {},

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
      },
      fileList: [],
      file: null,

      dhOpen: false,
      dhList: [],
      dhLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      this.phaseOption=this.dict.type.DETECTION_PHASE
      getRecordsList(this.queryParams).then(response=>{
        console.log(response,"---------------lhr")
        this.dataList = response.rows
        for (let i = 0; i < response.rows.length; i++) {
          for (let j = 0; j < this.phaseOption.length; j++) {
            if(response.rows[i].detectionLink == this.phaseOption[j].value) {
              this.dataList[i].detectionLink = this.phaseOption[j].label
            }
          }
          for (let j = 0; j < this.resultOption.length; j++) {
            if(response.rows[i].detectionResult == this.resultOption[j].value) {
              this.dataList[i].detectionResult1 = this.resultOption[j].label
            }
          }
        }
        this.total = response.total
        this.loading = false
      })
    },
    table_index(index){
      return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selection = selection
    },
    // 新增
    handleAdd() {
      this.upload.open = true
      this.upload.title = '四性方案记录'
    },
    submitFileForm() {
      const formData = new FormData();
      console.log(this.file)
      if (this.file == null) {
        this.$modal.msgWarning('请先上传文件')
      } else {
        const extension = this.file.name.substring(this.file.name.lastIndexOf('.') + 1);
        if (extension !== 'xml') {
          this.$message.warning('仅允许导入xml格式文件')
          return
        }
        formData.append("file", this.file);
        addRecords(formData).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.getList()
        })
        this.file = null
        this.fileList = []
        this.upload.open = false
      }
    },
    //开始上传文件
    uploadFile(content) {
      this.file = content.file
      console.log(content, this.file)
    },
    //限制上传附件
    fileLimit(file, fileList) {
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      const size = file.size / 1024 / 1024;
      if (extension !== 'xml') {
        this.$message.warning('仅允许导入xml格式文件')
      }
    },
    // 文件上传 - 文件选中后上传
    handleChange(file, fileList) {
      /* 自动上传改成true会导致重复触发，所以在handleChange上传文件*/
      //  防抖
      this.fileList = []
      let length = fileList.length
      this.fileList = [fileList[length - 1]]
      this.fileLimit(file, fileList);
      this.maxLength = Math.max(length, this.maxLength)
      setTimeout(() => {
        if (length === this.maxLength) {
          // 你的上传文件逻辑
          this.$refs.uploadComp.submit();
          this.fileLimit(file, fileList);
        }
      }, 100)
    },
    handleRemove() {
      this.fileList = []
    },
    closeDelDialog() {
      this.upload.open = false
      this.fileList = []
      this.dhOpen = false
    },
    // 修改
    handleUpdate() {
      const id = this.ids
      if(id.length == 0) {
        this.$modal.msgWarning("请选择一条数据进行修改")
        return;
      }
      if(id.length > 1) {
        this.$modal.msgWarning("只能选择一条数据进行修改")
        return;
      }
      console.log(this.selection)
      this.open = true
      this.passForm = this.selection[0]
      // if(this.selection[0].detectionResult == '检测成功') {
      //   this.passForm.detectionResult = '1'
      // } else {
      //   this.passForm.detectionResult = '0'
      // }
    },
    // 修改
    submitForm() {
      console.log(this.passForm)
      updateRecords(this.passForm).then(response => {
        this.open = false
        this.$modal.msgSuccess('修改成功')
        this.getList()
      })
    },
    cancel() {
      this.open = false
      this.getList()
    },
    // 删除
    handleDelete() {
      const ids = this.ids;
      if(ids.length == 0) {
        this.$modal.msgWarning("至少选择一条数据进行删除")
        return;
      }
      this.$modal.confirm('是否确认删除所选数据项？').then(function() {
        return deleteRecords(ids)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 导出
    handleExport() {
      const ids = this.ids;
      if(ids.length == 0 || ids.length > 1) {
        this.$modal.msgWarning("请选择一条数据进行导出")
        return;
      }
      // window.location.href='/archive/inspectionRecords/xmlExport?id='+ids
      this.download('/archive/inspectionRecords/xmlExport',{
        id: ids.toString()
      }, `InspectionRecords_${new Date().getTime()}.xml`)
    },
    // 查看详情
    handleDetail(row) {
      this.info = Object.assign({}, row);
      this.planOpen = true
      getRecordsDetail({pId: row.id}).then(response => {
        var treeData = response.data
        this.$nextTick(() => {
          console.log(treeData,"+++++")
          this.$refs.planRef.init(treeData, this.info)
        })
      })
    },
    handleDh(row) {
      this.dhList = []
      var arr = row.detectionDh.split(',')
      for (let i = 0; i < arr.length; i++) {
        this.dhList.push({
          dh: arr[i]
        })
      }
      this.dhOpen = true
    },
    planCancelTap() {
      this.planOpen = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

::v-deep .el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
</style>
